#include "CGUIIconSlot.h"
#include "EGUIIconFactoryEnums.h"

#include "IVideoDriver.h"
#include "IGUIEnvironment.h"
#include "IGUIButton.h"

namespace irr {
namespace gui {

CGUIIconSlot::CGUIIconSlot(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle, s32 slotGroup)
	: IGUIElement((EGUI_ELEMENT_TYPE)EGIEFT_ICON_SLOT , environment, parent, id, rectangle), 
	Texture(0), Full(false), SlotGroupID(slotGroup)
{

}

//! Destructor
CGUIIconSlot::~CGUIIconSlot()
{
	if (Texture)
		Texture->drop();
}

//! override the default add method
void CGUIIconSlot::removeChild(IGUIElement *child)
{
	// remove the child
	IGUIElement::removeChild(child);

	// search for icon children
	bool found=false;
	core::list<IGUIElement*>::Iterator it = Children.begin();
	for (; it != Children.end(); ++it)
		if ((*it)->getType() == (EGUI_ELEMENT_TYPE)EGIEFT_ICON )
		{
			found = true; // one of our children is an icon. this slot is full
		}

	if (found)
		Full = true;
	else
		Full = false;
}

//! override the default add method
void CGUIIconSlot::addChild(IGUIElement *child)
{
	if (child && child->getType() == (EGUI_ELEMENT_TYPE)EGIEFT_ICON)
	{
		Full = true;
	}

	IGUIElement::addChild(child);
}

bool CGUIIconSlot::OnEvent(SEvent e)
{

	// todo: capture drag over / drag off and drop events


	return IGUIElement::OnEvent(e);
}

//! Sets an image which should be displayed as the slot
void CGUIIconSlot::setImage(video::ITexture *img)
{
	if (Texture)
		Texture->drop();

	Texture = img;

	if (Texture)
		Texture->grab();
}

//! draws the element and its children
void CGUIIconSlot::draw()
{
	if (!IsVisible)
		return;

	irr::video::IVideoDriver* driver = Environment->getVideoDriver();

	if (Texture)
	{
		driver->draw2DImage(Texture, AbsoluteRect.UpperLeftCorner,
			core::rect<s32>(core::position2d<s32>(0,0), Texture->getOriginalSize()), &AbsoluteClippingRect );

		IGUIElement::draw();
	}
}

} // namespace gui
} // namespace irr
